//
//  AddressPhoneNumber.m
//  Weiweiyunshi
//
//  Created by 王译 on 17/2/14.
//  Copyright © 2017年 王译. All rights reserved.
//

#import "AddressPhoneNumber.h"
#import <Contacts/Contacts.h>
#import "PeopleModel.h"
#import <AddressBook/AddressBook.h>

@implementation AddressPhoneNumber

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self requestAuthorizationForAddressBook];

    }
    return self;
}

-(void)requestAuthorizationForAddressBook{
    
    //一. 获取授权信息
    ABAuthorizationStatus status = ABAddressBookGetAuthorizationStatus();

//    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
//    if (authorizationStatus == CNAuthorizationStatusNotDetermined) {
//        CNContactStore *contactStore = [[CNContactStore alloc] init];
//        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
//            if (granted) {
//                
//            } else {
//                NSLog(@"授权失败, error=%@", error);
//            }
//        }];
//    }
    
    switch (status) {
            
            //未授权, 需要授权
        case kABAuthorizationStatusNotDetermined:
            //获取通讯录 --> 从iOS6以后, 应该用这个方法
            
            //如果switch中代码过多, 应该用{}包一下
        {
            ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL, NULL), ^(bool granted, CFErrorRef error) {
                if (granted) {
                    NSLog(@"授权成功");
                    //获取联系人信息
                    [AddressPhoneNumber getAddressPhoneNumber];
                } else {
                    NSLog(@"授权失败");
                }
            });
        }
            break;
            
            //已授权
        case kABAuthorizationStatusAuthorized:
            [AddressPhoneNumber getAddressPhoneNumber];
            NSLog(@"已授权");
            break;
            
            //其他情况, 给用户提示
        case kABAuthorizationStatusRestricted:
        case kABAuthorizationStatusDenied:
            NSLog(@"请到设置中, 打开权限");
            break;
            
            
        default:
            break;
    }

}

+(NSMutableSet *)getOrgPhoneNumber{
    NSMutableArray *orgPhoneNumber = [NSMutableArray array];
    NSArray *arr = [PeopleModel sharedSingleton];
    for (id obj in arr) {
       [orgPhoneNumber addObject: [obj mobile]];
    }
    NSMutableSet *orgSet = [NSMutableSet setWithArray:orgPhoneNumber];
    return orgSet;
}

+(NSMutableSet *)getAddressPhoneNumber{
    NSMutableArray *phoneNumArr = [NSMutableArray array];
  /*  CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    if (authorizationStatus == CNAuthorizationStatusAuthorized) {
        NSLog(@"没有授权...");
    }
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        NSArray *phoneNumbers = contact.phoneNumbers;
        for (CNLabeledValue *labelValue in phoneNumbers) {
            CNPhoneNumber *phoneNumber = labelValue.value;
            
            NSMutableString *phoneStr = [[NSMutableString alloc]initWithString:phoneNumber.stringValue];
            
            NSString *strUrl = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
 //           NSLog(@"phone=%@", strUrl);
            [phoneNumArr addObject:strUrl];
        }
    }];*/
    
    
    ABAddressBookRef addressbook = ABAddressBookCreateWithOptions(NULL, NULL);
    
    //2. 获取通讯录内容
    CFArrayRef peopleArray = ABAddressBookCopyArrayOfAllPeople(addressbook);
    
    //3. 获取通讯录的个数
    CFIndex count = CFArrayGetCount(peopleArray);
    
    //4. 遍历通讯录内容
    for (CFIndex i = 0; i < count; i++) {
        
        //5. 获取单个通讯录内容 --> 获取单个联系人的信息
        ABRecordRef person = CFArrayGetValueAtIndex(peopleArray, i);
        
        //根据Person获取姓名和电话 --> 代码可以参考有界面通讯录的写法
        
        //6. 获取姓名
//        NSString *firstName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
//        NSString *lastName = CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
//        
//        NSLog(@"firstName: %@, lastName:%@", firstName, lastName);
        
        //7. 获取电话
        ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
        
        CFIndex phoneCount = ABMultiValueGetCount(phone);
        
        for (CFIndex i = 0; i < phoneCount; i++) {
            NSMutableString *phoneStr = CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, i));
            
            NSString *strUrl = [phoneStr stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            //           NSLog(@"phone=%@", strUrl);
            [phoneNumArr addObject:strUrl];
            
//            NSLog(@"phoneNumber: %@", phoneNumber);
        }
        
        //8. 释放CF对象
        CFRelease(phone);
    }
    //8. 释放CF对象
    CFRelease(peopleArray);
    CFRelease(addressbook);

    
    NSMutableSet *phoneSet = [NSMutableSet setWithArray:phoneNumArr];
    return phoneSet;
}

-(NSArray *)getSetArr{
    NSMutableSet *set = [AddressPhoneNumber getAddressPhoneNumber];
    NSMutableSet *set1 = [AddressPhoneNumber getOrgPhoneNumber];
    [set intersectSet:set1];
    NSArray *arr = [set allObjects];
    return arr;
}

@end
